﻿/*
-----------------------------------------------------------------------------
This source file is part of Cell Cloud.

Copyright (c) 2009-2011 Cell Cloud Team - cellcloudproject@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "TestSuite.h"

TaskList gTaskList;
LoggerManager* gLoggerManager = NULL;
boost::recursive_mutex gMutex;

//-----------------------------------------------------------------------
GlobalConfig::GlobalConfig(void)
{
	std::cout << "test setup" << std::endl;

	if (LoggerManager::getSingletonPtr() == NULL)
	{
		gLoggerManager = CELL_NEW LoggerManager();
		gLoggerManager->createLogger("test_executor.log", true, true);
	}

	String prename = "task_";
	for (int i = 0; i < TESTTASK_NUM; ++i)
	{
		TestTask* t = CELL_NEW TestTask(prename + StringConverter::toString(i));
		gTaskList.push_back(t);
	}
}
//-----------------------------------------------------------------------
GlobalConfig::~GlobalConfig(void)
{
	std::cout << "test teardown" << std::endl;

	TaskList::iterator iter, end = gTaskList.end();
	for (iter = gTaskList.begin(); iter != end; ++iter)
	{
		TestTask* t = (*iter);
		CELL_DELETE t;
	}

	if (gLoggerManager != NULL)
	{
		CELL_DELETE gLoggerManager;
		gLoggerManager = NULL;
	}
}


//-----------------------------------------------------------------------
ThreadPoolExecutorTester::ThreadPoolExecutorTester(void)
{
	
}
//-----------------------------------------------------------------------
ThreadPoolExecutorTester::~ThreadPoolExecutorTester(void)
{
}
//-----------------------------------------------------------------------
void ThreadPoolExecutorTester::testCachedPoolOneByOne(void)
{
	std::cout << "testCachedPoolOneByOne" <<std::endl;

	CachedThreadPool* executor = CELL_NEW CachedThreadPool("CachedPoolOneByOne", 5, 10);

	// Test core pool size
	BOOST_CHECK_EQUAL(executor->getCorePoolSize(), 5);
	// Test executing task counts
	BOOST_CHECK_EQUAL(executor->getActiveCount(), 0);

	resetTestTask(true);

	const int taskNum = TESTTASK_NUM;
	for (int i = 0; i < taskNum; ++i)
	{
		// Execute task
		// 仅使用第一个任务
		TestTask* task = gTaskList[0];
		executor->execute(task);
		TEST_PAUSE_CONDITION(task->isRunning());

		// Test active count
		BOOST_CHECK_EQUAL(executor->getActiveCount(), 1);

		task->stop();
		TEST_PAUSE_CONDITION_DELAY(!task->isRunning(), 5);

		TEST_PAUSE_TIMEOUT(5);

		// Test active count
		BOOST_CHECK_EQUAL(executor->getActiveCount(), 0);

		BOOST_CHECK_EQUAL(task->getCounts(), (i+1));
	}

	//std::cout << std::endl;
	resetTestTask(true);

	for (int i = 0; i < taskNum; ++i)
	{
		// Execute task
		// 依次执行每个任务
		TestTask* task = gTaskList[i];
		executor->execute(task);
		TEST_PAUSE_CONDITION(task->isRunning());

		// Test active count
		BOOST_CHECK_EQUAL(executor->getActiveCount(), 1);

		task->stop();
		TEST_PAUSE_CONDITION_DELAY(!task->isRunning(), 5);

		TEST_PAUSE_TIMEOUT(5);

		// Test active count
		BOOST_CHECK_EQUAL(executor->getActiveCount(), 0);

		BOOST_CHECK_EQUAL(task->getCounts(), 1);
	}

	CELL_DELETE executor;
}
//-----------------------------------------------------------------------
void ThreadPoolExecutorTester::testCachedPoolBase(void)
{
	std::cout << std::endl << "testCachedPoolBase" << std::endl;

	CachedThreadPool* executor = CELL_NEW CachedThreadPool("CachedPoolBase", 5, TESTTASK_NUM);
	// Test core pool size
	BOOST_CHECK_EQUAL(executor->getCorePoolSize(), 5);
	// Test executing task counts
	BOOST_CHECK_EQUAL(executor->getActiveCount(), 0);

	BOOST_CHECK_EQUAL(executor->getMaxPoolSize(), TESTTASK_NUM);

	TEST_PAUSE_TIMEOUT(100);

	resetTestTask(true);

	const int taskNum = TESTTASK_NUM;
	for (int i = 0; i < taskNum; ++i)
	{
		TestTask* task = gTaskList[i];
		executor->execute(task);
	}

	int workingNum = 0;
	while (workingNum != taskNum)
	{
		cell::Thread::sleep(100);
		workingNum = 0;
		for (int i = 0; i < taskNum; ++i)
		{
			TestTask* task = gTaskList[i];
			if (task->isRunning())
			{
				++workingNum;
			}
		}

		if (workingNum == taskNum)
			break;
	}

	/*std::cout << "xxx:" << workingNum << ", active:" << executor->getActiveCount()
		<< ", idle:" << executor->getIdleCount()
		<< ", task:" << executor->getTaskCount()
		<< ", list:" << executor->getTaskListSize()
		<< std::endl;*/

	// Test active count
	BOOST_CHECK_EQUAL(executor->getActiveCount(), taskNum);

	// Test task running counts
	for (int i = 0; i < taskNum; ++i)
	{
		TestTask* task = gTaskList[i];
		BOOST_CHECK_EQUAL(task->getCounts(), 1);
		task->stop();
	}

	int stoppedNum = 0;
	while (stoppedNum < taskNum)
	{
		cell::Thread::sleep(10);
		stoppedNum = 0;
		for (int i = 0; i < taskNum; ++i)
		{
			TestTask* task = gTaskList[i];
			if (!task->isRunning())
			{
				++stoppedNum;
			}
		}
	}

	TEST_PAUSE_TIMEOUT(1000);

	// Test active count
	BOOST_CHECK_EQUAL(executor->getActiveCount(), 0);

	executor->awaitExecution();
	CELL_DELETE executor;
}
//-----------------------------------------------------------------------
void ThreadPoolExecutorTester::testCachePoolOverflow(void)
{
	std::cout << std::endl << "testCachePoolOverflow" << std::endl;

	CachedThreadPool* executor = CELL_NEW CachedThreadPool("testCachePoolOverflow", 5, 10);

	resetTestTask(false);

	const int numTask = TESTTASK_NUM;
	for (int i = 0; i < numTask; ++i)
	{
		TestTask* task = gTaskList[i];
		executor->execute(task);
	}

	std::cout << "Wait executing..." << std::endl;

	bool over = false;
	int count = 0;
	while (!over)
	{
		cell::Thread::sleep(100);

		count = 0;
		for (int i = 0; i < numTask; ++i)
		{
			TestTask* task = gTaskList[i];
			if (task->getCounts() == 1)
				++count;
		}

		if (count == numTask)
			over = true;
	}

	executor->awaitExecution();

	std::cout << std::endl;
	std::cout << "active: " << executor->getActiveCount() << std::endl;
	std::cout << "idle  : " << executor->getIdleCount() << std::endl;
	std::cout << "task  : " << executor->getTaskCount() << std::endl;
	std::cout << "list  : " << executor->getTaskListSize() << std::endl;

	CELL_DELETE executor;
}
//-----------------------------------------------------------------------
void ThreadPoolExecutorTester::testFixedPoolBase(void)
{
	std::cout << std::endl;

	FixedThreadPool* executor = CELL_NEW FixedThreadPool("FixedPoolBase", 10);

	// Check core pool size
	BOOST_CHECK_EQUAL(executor->getCorePoolSize(), 10);
	// Check executing task counts
	BOOST_CHECK_EQUAL(executor->getActiveCount(), 0);

	resetTestTask(false);

	const int taskNum = 10;
	for (int i = 0; i < taskNum; ++i)
	{
		// Execute task
		TestTask* task = gTaskList[i];
		executor->execute(task);
	}

	executor->awaitExecution();

	for (int i = 0; i < taskNum; ++i)
	{
		TestTask* task = gTaskList[i];
		BOOST_CHECK_EQUAL(task->getCounts(), 1);
	}

	CELL_DELETE executor;
}
//-----------------------------------------------------------------------
void ThreadPoolExecutorTester::testFixedPoolOverload(void)
{
	std::cout << std::endl;

	FixedThreadPool* executor = CELL_NEW FixedThreadPool("FixedPoolOverload", 10);

	// Check core pool size
	BOOST_CHECK_EQUAL(executor->getCorePoolSize(), 10);
	// Check executing task counts
	BOOST_CHECK_EQUAL(executor->getActiveCount(), 0);

	resetTestTask(false);

	const int taskNum = 20;
	for (int i = 0; i < taskNum; ++i)
	{
		// Execute task
		TestTask* task = gTaskList[i];
		executor->execute(task);
	}

	executor->awaitExecution();

	for (int i = 0; i < taskNum; ++i)
	{
		TestTask* task = gTaskList[i];
		BOOST_CHECK_EQUAL(task->getCounts(), 1);
	}

	CELL_DELETE executor;
}
//-----------------------------------------------------------------------
void ThreadPoolExecutorTester::resetTestTask(bool spinning)
{
	TaskList::iterator iter, end = gTaskList.end();
	for (iter = gTaskList.begin(); iter != end; ++iter)
	{
		TestTask* t = (*iter);
		t->stop();
		t->spinning(spinning);
		t->resetCounts();
	}
}



//-----------------------------------------------------------------------
ThreadPoolExecutorTestSuite::ThreadPoolExecutorTestSuite(void)
	: test_suite("ThreadPoolExecutorTestSuite")
{
	// add member function test cases to a test suite
	boost::shared_ptr<ThreadPoolExecutorTester> instance(new ThreadPoolExecutorTester());

	test_case* testCachedPoolOneByOne = BOOST_CLASS_TEST_CASE( &ThreadPoolExecutorTester::testCachedPoolOneByOne, instance );
	test_case* testCachedPoolBase = BOOST_CLASS_TEST_CASE( &ThreadPoolExecutorTester::testCachedPoolBase, instance );
	test_case* testCachePoolOverflow = BOOST_CLASS_TEST_CASE( &ThreadPoolExecutorTester::testCachePoolOverflow, instance );
	//test_case* testFixedPoolBase = BOOST_CLASS_TEST_CASE( &ThreadPoolExecutorTester::testFixedPoolBase, instance );
	//test_case* testFixedPoolOverload = BOOST_CLASS_TEST_CASE( &ThreadPoolExecutorTester::testFixedPoolOverload, instance );

	add(testCachedPoolOneByOne);
	add(testCachedPoolBase);
	add(testCachePoolOverflow);
	//add(testFixedPoolBase);
	//add(testFixedPoolOverload);
}
//-----------------------------------------------------------------------
ThreadPoolExecutorTestSuite::~ThreadPoolExecutorTestSuite(void)
{
}



//-----------------------------------------------------------------------
TestTask::TestTask(const String& name) : mName(name), mCounts(0),
	mRunning(false), mSpinning(true)
{
	//std::cout << "[test] Create task : " << mName << std::endl;
}
//-----------------------------------------------------------------------
TestTask::~TestTask(void)
{
}
//-----------------------------------------------------------------------
void TestTask::spinning(bool spin)
{
	mSpinning = spin;
}
//-----------------------------------------------------------------------
bool TestTask::isRunning(void)
{
	return mRunning;
}
//-----------------------------------------------------------------------
void TestTask::stop(void)
{
	mRunning = false;
}
//-----------------------------------------------------------------------
void TestTask::run(void)
{
	if (mRunning)
		return;

	++mCounts;
	{
		boost::recursive_mutex::scoped_lock lock(gMutex);
		std::cout << "[test] Run task : " << mName << " (" << mCounts << ")" << std::endl;
	}
	mRunning = true;

	if (mSpinning)
	{
		while (mRunning)
		{
			Thread::sleep(1);
		}
	}
	else
	{
		mRunning = false;
	}
}
